package servlet;

import bean.SingleConfig;
import dao.AdminDao;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.RequestUtil;
import util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 配置表的servlet
 *
 * @author 邓晴予
 */
public class ConfigServlet extends HttpServlet {
    private AdminDao adminDao = new AdminDao();

    /**
     * 获取配置表的所有记录
     *
     * @author 邓晴予
     */
    @SuppressWarnings("unchecked")
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResponseUtil.write(resp, JsonWrapper.builder().setStatus(200).setMsg("success")
            .setDataEntries(JsonWrapper.parseFromObject(SingleConfig.getInstance().val())).build());
    }

    /**
     * 管理员修改config表的值
     *
     * @author 邓晴予
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        JSONObject jo = RequestUtil.getJsonFromRequest(req);
        if (jo == null) {
            ResponseUtil.writeBadRequest(resp);
            return;
        }
        String adminId = (String) jo.get("adminId");
        String type = (String) jo.get("type");
        String value = (String) jo.get("value");
        if (adminId == null || type == null || value == null) {
            ResponseUtil.writeBadRequest(resp);
            return;
        }
        boolean havePermission = adminDao.havePermission(adminId, "updateconfig");
        if (havePermission) {
//			该管理员有权限进行修改config表
            boolean isSuccess;
            try {
                SingleConfig.getInstance().set(type, value);
                ResponseUtil.writeSuccess(resp);
            } catch (Exception e) {
                e.printStackTrace();
                ResponseUtil.write(resp, 401, "failed");
            }
        } else {
//			该管理员没有权限进行修改config表
            ResponseUtil.write(resp, 403, "failed");
        }
    }
}
